package com.wch.friend.filter;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class JwtFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前后端约定：前端请求微服务时需要添加头信息Authorization ,内容为Bearer+空格 +token
        System.out.println(this.getClass().getName()+"经过了拦截器");

        String authHeader = request.getHeader("Authorization");

        if(null != authHeader && authHeader.startsWith("Bearer_")){
            String token = authHeader.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            if(null != claims){
                if("admin".equals(claims.get("roles"))){
                    request.setAttribute("admin_roles",claims);
                }
                if("user".equals(claims.get("roles"))){
                    request.setAttribute("user_roles",claims);
                }
            }
        }
        return true;
    }
}
